package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.*;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信户用登录
     * @param userLoginDto
     * @return
     */
    @Override
    public LoginVo getUser(UserLoginRequestDto userLoginDto) {
        if (userLoginDto == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }
        //调用微信api,获取微信用户openid
        String openid = wechatService.getOpenId(userLoginDto.getCode());
        //获取微信用户手机号phone
        String phone = wechatService.getPhone(userLoginDto.getPhoneCode());

        //查询数据库中微信用户信息
        Member member = memberMapper.selectWechatUser(openid);

        //如果查询的用户为空，则就新增用户信息
        if (ObjectUtil.isEmpty(member)) {
            member = Member.builder()
                    .phone(phone)
                    .openId(openid)
                    .name("微信用户"+ StringUtils.substring(phone,7))
                    .build();
            memberMapper.insertWechatUser(member);
        }
        //比较该用户登录的手机号与查询到的原有手机号码
        else if (!phone.equals(member.getPhone())) { //如果不一样就更新信息
            member.setPhone(phone);
            memberMapper.updateWechatUser(member);
        }

        //将用户id存入token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());
        //生成token
        String token = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(), jwtProperties.getTtl(), claims);

        //创建loginVo对象
        LoginVo loginVo = LoginVo.builder()
                .nickName(member.getName())
                .token(token)
                .build();
        return loginVo;
    }


    @Autowired
    private ContractService contractService;

    @Autowired
    private MemberElderService memberElderService;

    @Autowired
    private OrderService orderService;

    /**
     * 分页查询用户列表
     *
     * @param page     当前页码
     * @param pageSize 每页数量
     * @param phone    手机号
     * @param nickname 昵称
     * @return 分页结果
     */
    @Override
    public PageResponse<MemberVo> page(Integer page, Integer pageSize, String phone, String nickname) {
        PageHelper.startPage(page, pageSize);
        Page<List<Member>> listPage = memberMapper.page(phone, nickname);

        PageResponse<MemberVo> pageResponse = PageResponse.of(listPage, MemberVo.class);
        List<Long> ids = pageResponse.getRecords().stream().map(MemberVo::getId).distinct().collect(Collectors.toList());

        pageResponse.getRecords().forEach(v -> {
            List<ContractVo> contractVos = contractService.listByMemberPhone(v.getPhone());
            v.setIsSign(contractVos.isEmpty() ? "否" : "是");
            List<OrderVo> orderVos = orderService.listByMemberId(v.getId());
            v.setOrderCount(orderVos.size());
            List<MemberElderVo> memberElderVos = memberElderService.listByMemberId(v.getId());
            List<String> collect = memberElderVos.stream().map(m -> m.getElderVo().getName()).collect(Collectors.toList());
            v.setElderNames(String.join(",", collect));
        });
        return pageResponse;
    }

    /**
     * 根据id查询用户
     * @param id 用户id
     * @return 用户信息
     */
    @Override
    public Member getById(Long id) {
        return memberMapper.selectById(id);
    }
}

